package com.mp.chart.charts;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.mp.chart.components.AJXAxis;
import com.mp.chart.components.AJYAxis;
import com.mp.chart.components.MarkerView;
import com.mp.chart.components.YAxis;
import com.mp.chart.data.Entry;
import com.mp.chart.data.LineData;
import com.mp.chart.data.LineDataSet;
import com.mp.chart.formatter.FillFormatter;
import com.mp.chart.interfaces.AJProvider;
import com.mp.chart.interfaces.LineDataProvider;
import com.mp.chart.listener.AJChartTouchListener;
import com.mp.chart.listener.OnScrollDataListener;
import com.mp.chart.listener.OnSyncChartListener;
import com.mp.chart.markerview.HightCircleMarkerView;
import com.mp.chart.renderer.AJXAxisRenderer;
import com.mp.chart.renderer.AJYAxisRenderer;
import com.mp.chart.renderer.MinutesLineChartRenderer;
import com.mp.chart.utils.Highlight;
import com.mp.chart.utils.SelectionDetail;
import com.mp.chart.utils.Utils;
import com.mp.chart.view.ShinePointView;

import java.util.List;

/**
 * 重写折线图
 */
public class MinutesLineChart extends BarLineChartBase<LineData> implements LineDataProvider, FillFormatter, AJProvider {

    private FillFormatter mFillFormatter;
    private MarkerView quoteInfoMarkerView;
    private MarkerView mTopMarkerView;
    private MarkerView mLeftMarkerView;
    private MarkerView mRightMarkerView;
    private AJChartTouchListener mMarketTouchListener;
    private MarkerView mXAxisMarkerView;
    private ShinePointView pointView;
    private HightCircleMarkerView hightCircleMarkerView;

    public MinutesLineChart(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MinutesLineChart(Context context) {
        super(context);
    }

    public MinutesLineChart(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void init() {
        super.init();
        setDescription("");
        mXAxis = new AJXAxis();
        mAxisLeft = new AJYAxis(YAxis.AxisDependency.LEFT);
        mAxisRight = new AJYAxis(YAxis.AxisDependency.RIGHT);


        mXAxisRenderer = new AJXAxisRenderer(this, mViewPortHandler, (AJXAxis) mXAxis, mLeftAxisTransformer);
        mAxisRendererLeft = new AJYAxisRenderer(mViewPortHandler, (AJYAxis) mAxisLeft, mLeftAxisTransformer);
        mAxisRendererRight = new AJYAxisRenderer(mViewPortHandler, (AJYAxis) mAxisRight, mRightAxisTransformer);
        mRenderer = new MinutesLineChartRenderer(this, mAnimator, mViewPortHandler);
        mChartTouchListener = new AJChartTouchListener(this, mViewPortHandler.getMatrixTouch());

        mMarketTouchListener = (AJChartTouchListener) mChartTouchListener;
        mFillFormatter = this;
    }

    public void setLongPressEnable(boolean value) {
        mMarketTouchListener.setLongPressEnable(value);
    }

    @Override
    protected void calcMinMax() {
        super.calcMinMax();
        if (mDeltaX == 0 && mData.getYValCount() > 0)
            mDeltaX = 1;

    }

    @Override
    public void setFillFormatter(FillFormatter formatter) {

        if (formatter == null) {
            formatter = this;
        } else {
            mFillFormatter = formatter;
        }
    }

    @Override
    public FillFormatter getFillFormatter() {
        return mFillFormatter;
    }

    @Override
    public LineData getLineData() {
        return mData;
    }


    @Override
    public AJXAxis getXAxis() {
        return (AJXAxis) super.getXAxis();
    }

    @Override
    public AJYAxis getAxisLeft() {
        return (AJYAxis) super.getAxisLeft();
    }

    @Override
    public AJYAxis getAxisRight() {
        return (AJYAxis) super.getAxisRight();
    }

    @Override
    public float getFillLinePosition(LineDataSet dataSet, LineData data, float chartMaxY, float chartMinY) {


        return mAxisLeft.getAxisMinValue();

    }

    public void setTopMarkerView(MarkerView topMarkerView) {
        this.mTopMarkerView = topMarkerView;
    }

    public void setQuoteInfoMarkerView(MarkerView quoteInfoMarkerView) {
        this.quoteInfoMarkerView = quoteInfoMarkerView;
    }

    public void setLeftMarkerView(MarkerView leftMarkerView) {
        this.mLeftMarkerView = leftMarkerView;
    }

    public void setXAxisMarkerView(MarkerView leftMarkerView) {
        this.mXAxisMarkerView = leftMarkerView;
    }

    public void setRightMarkerView(MarkerView rightMarkerView) {
        this.mRightMarkerView = rightMarkerView;
    }

    public void setHighLightCircleView(HightCircleMarkerView highLightCircleView) {
        this.hightCircleMarkerView = highLightCircleView;
    }

    /**
     * Returns the Highlight object (contains x-index and DataSet index) of the
     * selected showapi_res_body at the given touch point inside the Line-, Scatter-, or
     * CandleStick-Chart.
     * 重写分时根据touch设置高亮显示
     *
     * @param x
     * @param y
     * @return
     */
    public Highlight getHighlightByTouchPoint(float x, float y) {

        if (mDataNotSet || mData == null) {
//            Log.e(LOG_TAG, "Can't select by touch. No data set.");
            return null;
        }

        // create an array of the touch-point
        float[] pts = new float[2];
        pts[0] = x;

        // take any transformer to determine the x-axis showapi_res_body
        mLeftAxisTransformer.pixelsToValue(pts);

        double xTouchVal = pts[0];

        double base = Math.floor(xTouchVal);

        double touchOffset = mDeltaX * 0.025;

        // touch out of com.mp.chart
        if (xTouchVal < -touchOffset || xTouchVal > mDeltaX + touchOffset)
            return null;

        if (base < 0)
            base = 0;
        if (base >= mDeltaX)
            base = mDeltaX - 1;

        int xIndex = (int) base;

        // check if we are more than half of a x-showapi_res_body or not
        if (xTouchVal - base > 0.5) {
            xIndex = (int) base + 1;
        }

        List<SelectionDetail> valsAtIndex = getSelectionDetailsAtIndex(xIndex);
        float leftdist = Utils.getMinimumDistance(valsAtIndex, y, YAxis.AxisDependency.LEFT);
        float rightdist = Utils.getMinimumDistance(valsAtIndex, y, YAxis.AxisDependency.RIGHT);

        if (mData.getFirstRight() == null)
            rightdist = Float.MAX_VALUE;
        if (mData.getFirstLeft() == null)
            leftdist = Float.MAX_VALUE;

        YAxis.AxisDependency axis = leftdist < rightdist ? YAxis.AxisDependency.LEFT : YAxis.AxisDependency.RIGHT;

        int dataSetIndex = Utils.getClosestDataSetIndex(valsAtIndex, y, axis);
        Log.e("tenface", "dataSetIndex" + dataSetIndex);

        /*修复数据不全情况下,快速高亮滑动导致高亮不在最右侧的bug*/
        if (dataSetIndex == -1) {
            xIndex = getValueCount() / 2 - 1;
            dataSetIndex = 0;
            highlightTouch(new Highlight(xIndex, dataSetIndex));
            Log.e("tenface", "xIndex: " + xIndex);
            /*空白处设置高亮值*/
            highlightValues(new Highlight[]{
                    new Highlight(xIndex, dataSetIndex)
            });
        }
//        Log.e("%%%", "xIndex" + xIndex);
        return new Highlight(xIndex, dataSetIndex);
    }

    /*
    *mViewPortHandler以父布局左上角为（0,0）点
    *mViewPortHandler.contentTop()表示图表框框距离父布局上边界的距离 px
    * mViewPortHandler.contentBottom()表示图表框框距离父布局上边界的距离 px
    *mViewPortHandler.contentLeft()表示图表框框距离父布局左边界的距离 px
    *mViewPortHandler.contentRight()表示图表框框距离父布局左边界的距离 px
    *
    * */
    protected void drawMarkers(Canvas canvas) {
        if (mTopMarkerView == null && mLeftMarkerView == null && mRightMarkerView == null && mXAxisMarkerView == null) {
            return;
        }
        if (!mDrawMarkerViews || !valuesToHighlight())
            return;

        for (int i = 0; i < mIndicesToHightlight.length; i++) {
            int xIndex = mIndicesToHightlight[i].getXIndex();
            int dataSetIndex = mIndicesToHightlight[i].getDataSetIndex();

            if (xIndex <= mDeltaX && xIndex <= mDeltaX * mAnimator.getPhaseX()) {

                Entry e = mData.getEntryForHighlight(mIndicesToHightlight[i]);
                // make sure entry not null
                if (e == null || e.getXIndex() != mIndicesToHightlight[i].getXIndex())
                    continue;

                float[] pos = getMarkerPosition(e, dataSetIndex);
//                Log.e("position", pos[0] + "," + pos[1]);
                /*
                * 一下内容画marker的位置
                * */
                /*折线图左边高亮，右边没有*/
                if (mLeftMarkerView != null && mRightMarkerView == null) {
                    measureMarkerView(mLeftMarkerView, dataSetIndex, e);
                    float x = 0;
                    float y = 0;
                    /*如果高亮的x>图表的中心宽，则显示在左边  centerX是以图表的左下角为来算的px单位*/
                    if (pos[0] > mViewPortHandler.getContentRect().centerX()) {

                        //x = mViewPortHandler.contentLeft() - mLeftMarkerView.getXOffset();
                        x = mViewPortHandler.contentLeft() - mLeftMarkerView.getXOffset() - mLeftMarkerView.getWidth();
                    } else {
                        //x = mViewPortHandler.contentRight() + mLeftMarkerView.getXOffset() - mLeftMarkerView.getWidth();
                        x = mViewPortHandler.contentRight() + mLeftMarkerView.getXOffset();
                    }
                    if (pos[1] + mLeftMarkerView.getYOffset() < mViewPortHandler.contentTop()) {
                        y = mViewPortHandler.contentTop() - mLeftMarkerView.getYOffset();
                    } else if (pos[1] - mLeftMarkerView.getYOffset() > mViewPortHandler.contentBottom()) {
                        y = mViewPortHandler.contentBottom() + mLeftMarkerView.getYOffset();
                    } else {
                        y = pos[1];
                    }


                    mLeftMarkerView.draw(canvas, x, y);
                    /*mleftMarkerView==null || mrightMarkerView!=null && mleftMarkerView!=null 等价于后面两个交集*/
                    /*左右边有 限制左边，右边下面进行限制*/
                } else if (mLeftMarkerView != null) {
                    measureMarkerView(mLeftMarkerView, dataSetIndex, e);
                    if (pos[1] + mLeftMarkerView.getYOffset() < mViewPortHandler.contentTop()) {
                        //mLeftMarkerView.draw(canvas, mViewPortHandler.offsetLeft(), mViewPortHandler.contentTop() - mLeftMarkerView.getYOffset());
                        mLeftMarkerView.draw(canvas, mViewPortHandler.contentLeft() - mViewPortHandler.offsetLeft() - mLeftMarkerView.getWidth(), mViewPortHandler.contentTop() - mLeftMarkerView.getYOffset());
                    } else if (pos[1] - mLeftMarkerView.getYOffset() > mViewPortHandler.contentBottom()) {
                        //mLeftMarkerView.draw(canvas, mViewPortHandler.offsetLeft(), mViewPortHandler.contentBottom() + mLeftMarkerView.getYOffset());
                        mLeftMarkerView.draw(canvas, mViewPortHandler.contentLeft() - mViewPortHandler.offsetLeft() - mLeftMarkerView.getWidth(), mViewPortHandler.contentBottom() + mLeftMarkerView.getYOffset());
                    } else {
                        mLeftMarkerView.draw(canvas, mViewPortHandler.contentLeft() - mLeftMarkerView.getWidth(), pos[1] - mLeftMarkerView.getHeight() / 2);
                    }

                }
                if (mRightMarkerView != null) {
                    measureMarkerView(mRightMarkerView, dataSetIndex, e);

                    if (pos[1] + mRightMarkerView.getYOffset() < mViewPortHandler.contentTop()) {
                        mRightMarkerView.draw(canvas, mViewPortHandler.contentRight() - mViewPortHandler.offsetLeft() + mRightMarkerView.getWidth(), mViewPortHandler.contentTop() - mRightMarkerView.getYOffset());
                    } else if (pos[1] - mLeftMarkerView.getYOffset() > mViewPortHandler.contentBottom()) {
                        mRightMarkerView.draw(canvas, mViewPortHandler.contentRight() - mViewPortHandler.offsetLeft() + mRightMarkerView.getWidth(), mViewPortHandler.contentBottom() + mRightMarkerView.getYOffset());
                    } else {
                        mRightMarkerView.draw(canvas, mViewPortHandler.contentRight(), pos[1] - mLeftMarkerView.getHeight() / 2);
                    }
                }

                if (mXAxisMarkerView != null) {
                    measureMarkerView(mXAxisMarkerView, dataSetIndex, e);
                    float x = pos[0];
                    float y1 = mViewPortHandler.contentBottom();
                    float y2 = mViewPortHandler.contentTop();
                    if (pos[0] + mXAxisMarkerView.getXOffset() < mViewPortHandler.contentLeft()) {
                        x = mViewPortHandler.contentLeft() - mXAxisMarkerView.getXOffset();
                    } else if (pos[0] - mXAxisMarkerView.getXOffset() > mViewPortHandler.contentRight()) {
                        x = mViewPortHandler.contentRight() + mXAxisMarkerView.getXOffset();
                    } else {
                        x = pos[0];
                    }
                    mXAxisMarkerView.draw(canvas, x, y1);

                }

                //长按时的View显示
                if (quoteInfoMarkerView != null) {
                    drawQuoteInfoView(canvas, i, xIndex, e);
                }

                /*高亮圆点*/
                if (hightCircleMarkerView != null) {
                    hightCircleMarkerView.draw(canvas, pos[0] - hightCircleMarkerView.getMeasuredWidth(), pos[1] - hightCircleMarkerView.getMeasuredHeight());
                }

            }
        }
    }

    /***
     * 画chart上的悬浮view
     * @param canvas canvas
     * @param i for循环索引
     * @param xIndex  数据索引
     * @param e Entry
    //     * @param quoteInfoList List，存入所需的数据，0-昨收，1-时间，2-价格，3-均价，4-涨跌幅
     */
    private void drawQuoteInfoView(Canvas canvas, int i, int xIndex, Entry e) {
        if (quoteInfoMarkerView != null) {
            quoteInfoMarkerView.refreshContent(e, i);
            quoteInfoMarkerView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            quoteInfoMarkerView.layout(0, 0, quoteInfoMarkerView.getMeasuredWidth(), quoteInfoMarkerView.getMeasuredHeight());
            if (xIndex >= 0 && xIndex < 180) {
                quoteInfoMarkerView.draw(canvas, mViewPortHandler.contentWidth() - quoteInfoMarkerView.getWidth() + mViewPortHandler.offsetLeft(), mViewPortHandler.contentTop() - mViewPortHandler.offsetTop());
            } else if (xIndex >= 180) {
                quoteInfoMarkerView.draw(canvas, mViewPortHandler.contentLeft(), mViewPortHandler.contentTop() - mViewPortHandler.offsetTop());
            }
        }
    }

    private void measureMarkerView(MarkerView markerView, int dataSetIndex, Entry e) {
        //更新marker上数据
        markerView.refreshContent(e, dataSetIndex);
        /*计算大小*/
        markerView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        markerView.layout(0, 0, markerView.getMeasuredWidth(),
                markerView.getMeasuredHeight());
    }

    protected void calcModulus() {
        mXAxis.mAxisLabelModulus = 1;
    }

    /*line高亮触碰后*/
    int select = 0;

    public Entry highlightTouchWithoutEvent(Highlight high, int isSelect) {
        this.select = isSelect;
        Entry e = null;

        if (high == null) {
            if (select == 1) {
                mIndicesToHightlight = new Highlight[]{new Highlight(mData.getXValCount(), 0)};
            } else if (select == 0) {
                mIndicesToHightlight = null;
            }
        } else {

            if (mLogEnabled)
                Log.i(LOG_TAG, "Highlighted: " + high.toString());

            e = mData.getEntryForHighlight(high);
            if (e == null) {
                mIndicesToHightlight = null;
                high = null;
            } else {
                // set the indices to highlight
                mIndicesToHightlight = new Highlight[]{
                        high
                };
            }
        }

        // redraw the com.mp.chart
        invalidate();
        return e;
    }

    public void setShinePointView(ShinePointView pointView) {

        if (pointView == null) {
            return;
        }

        if (this.pointView != null) {
            removeView(this.pointView);
        }

        this.pointView = pointView;
        this.pointView.refreshView();
        addView(this.pointView);

    }

    boolean showPoint = true;

    public void setShinePointStatus(boolean isShow){
        this.showPoint = isShow;
        if (showPoint){
            this.pointView.setVisibility(VISIBLE);
        }else {
            this.pointView.setVisibility(GONE);
        }

    }

  /*  public void setHighLightCircleView(HightCircleMarkerView circleView) {

        if (circleView == null) {
            return;
        }

        if (this.circleView != null) {
            removeView(this.circleView);
        }

        this.circleView = circleView;
        addView(this.circleView);

    }*/

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        drawShinePointView();

    }


    /*设置呼吸灯位置*/
    private void drawShinePointView() {

        if (pointView == null) {
            return;
        }

        if (mDataNotSet) {
            pointView.layout(0, 0, 0, 0);
            return;
        }
//获取第一组数据（成交价）
        List<Entry> list = getData().getDataSetByIndex(0).getYVals();

        if (list.size() > 0) {
            //获取成交价中的最后一条数据
            Entry entry = list.get(list.size() - 1);

            float[] pos = {entry.getXIndex(), entry.getVal()};
            mLeftAxisTransformer.pointValuesToPixel(pos);//将点坐标转换为px
            pointView.layout((int) (pos[0] - pointView.getMeasuredWidth() / 2),
                    (int) (pos[1] - pointView.getMeasuredHeight() / 2),
                    (int) (pos[0] + pointView.getMeasuredWidth() / 2),
                    (int) (pos[1] + pointView.getMeasuredHeight() / 2));
        }


    }

    @Override
    public OnScrollDataListener getOnScrollDataListener() {
        return null;
    }

    @Override
    public void setOnScrollDataListener(OnScrollDataListener l) {

    }

    @Override
    public void setOnSyncChartListener(OnSyncChartListener l) {

    }

    @Override
    public void setOnLoadingViewListener(AJChartTouchListener.OnLoadingViewListener l) {

    }

    @Override
    public boolean getDrawbarEnable() {
        return false;
    }

    @Override
    public boolean getHighLightStyle() {
        return false;
    }

    @Override
    public void syncMatrix(float transx, float scalex, boolean islimit) {

    }


}
